const api = require('../../utils/api.js');

Page({
  data: {
    conversations: [],
    currentPage: 1,
    perPage: 5,
    hasMore: true,
    loading: false,
    refreshing: false,
    searchKeyword: '',
    activeFilter: 'all',
    
    // 人设配置
    personas: {
      'professional': { 
        name: '心研顾问', 
        avatar: '/assets/avatars/professional.png'
      },
      'su_shi': { 
        name: '东坡先生', 
        avatar: '/assets/avatars/su_shi.png'
      },
      'therapist': { 
        name: '安心博士', 
        avatar: '/assets/avatars/therapist.png'
      },
      'youthful': { 
        name: '小阳', 
        avatar: '/assets/avatars/youthful.png'
      },
      'wise_elder': { 
        name: '明心爷爷', 
        avatar: '/assets/avatars/wise_elder.png'
      },
      'artistic': { 
        name: '星语', 
        avatar: '/assets/avatars/artistic.png'
      },
      'tech_rational': { 
        name: '亚里士多德', 
        avatar: '/assets/avatars/tech_rational.png'
      },
      'humorous': { 
        name: '笑笑', 
        avatar: '/assets/avatars/humorous.png'
      },
      'nature_healer': { 
        name: '林深', 
        avatar: '/assets/avatars/nature_healer.png'
      },
      'life_coach': { 
        name: '远航', 
        avatar: '/assets/avatars/life_coach.png'
      },
      'animal_companion': { 
        name: '喵喵', 
        avatar: '/assets/avatars/animal_companion.png'
      },
      'spiritual_guide': { 
        name: '弗洛伊德', 
        avatar: '/assets/avatars/spiritual_guide.png'
      },
      'wu_ze_tian': { 
        name: '武则天', 
        avatar: '/assets/avatars/wu_ze_tian.png'
      },
      'lu_xun': { 
        name: '树人先生', 
        avatar: '/assets/avatars/lu_xun.png'
      },
      'woolfe': { 
        name: '伍尔芙', 
        avatar: '/assets/avatars/woolfe.png'
      },
      'mark_twain': { 
        name: '老马克', 
        avatar: '/assets/avatars/mark_twain.png'
      }
    }
  },

  onLoad: function() {
    this.loadConversations();
  },

  onShow: function() {
    this.refreshData();
  },

  // 加载对话列表
  loadConversations: function() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });

    api.getConversationHistory(this.data.currentPage, this.data.perPage)
      .then(res => {
        console.log('对话历史响应:', res);
        
        if (res.code === 200 && res.data) {
          const newConversations = res.data.conversations || [];
          
          // 处理对话数据 - 预处理头像、名称和时间
          const processedConversations = newConversations.map(conv => {
            const personaConfig = this.data.personas[conv.persona];
            return {
              ...conv,
              is_favorite: false,
              avatar: personaConfig ? personaConfig.avatar : '/static/avatars/default.png',
              personaName: personaConfig ? personaConfig.name : '未知',
              // 处理时间显示
              startTimeStr: this.formatStartTime(conv.start_time),
              lastActiveStr: this.formatLastActive(conv.last_active_time)
            };
          });

          this.setData({
            conversations: this.data.currentPage === 1 ? 
              processedConversations : 
              [...this.data.conversations, ...processedConversations],
            hasMore: newConversations.length === this.data.perPage,
            currentPage: this.data.currentPage + 1
          });
        }
      })
      .catch(error => {
        console.error('加载对话历史失败:', error);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ loading: false });
      });
  },

  // 刷新数据
  refreshData: function() {
    this.setData({
      currentPage: 1,
      hasMore: true,
      conversations: []
    });
    this.loadConversations();
  },

  // 下拉刷新
  onRefresh: function() {
    this.setData({ refreshing: true });
    this.refreshData();
    setTimeout(() => {
      this.setData({ refreshing: false });
    }, 1000);
  },

  // 加载更多
  loadMore: function() {
    this.loadConversations();
  },

  // 搜索输入
  onSearchInput: function(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  // 执行搜索
  onSearch: function() {
    console.log('搜索关键词:', this.data.searchKeyword);
    wx.showToast({
      title: '搜索功能开发中',
      icon: 'none'
    });
  },

  // 设置筛选
  setFilter: function(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      activeFilter: filter
    });
    this.refreshData();
  },

  // 打开对话详情
  openConversation: function(e) {
    const conversationId = e.currentTarget.dataset.id;
    const topic = e.currentTarget.dataset.topic;
    const persona = e.currentTarget.dataset.persona;
    
    console.log('点击对话:', {
      conversationId: conversationId,
      topic: topic,
      persona: persona
    });
    
    wx.navigateTo({
      url: `/pages/talk/talk?conversationId=${conversationId}&topic=${encodeURIComponent(topic)}&persona=${persona}`
    });
  },

  // 开始新对话
  startNewConversation: function() {
    wx.navigateTo({
      url: '/pages/conversation/conversation'
    });
  },

  // 切换收藏状态
  toggleFavorite: function(e) {
    const conversationId = e.currentTarget.dataset.id;
    const conversations = this.data.conversations.map(conv => {
      if (conv.conversation_id === conversationId) {
        return { ...conv, is_favorite: !conv.is_favorite };
      }
      return conv;
    });
    
    this.setData({ conversations });
    
    const conv = conversations.find(c => c.conversation_id === conversationId);
    wx.showToast({
      title: conv.is_favorite ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 删除对话
  deleteConversation: function(e) {
    const conversationId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '删除后无法恢复，确定要删除这个对话吗？',
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          const conversations = this.data.conversations.filter(
            conv => conv.conversation_id !== conversationId
          );
          this.setData({ conversations });
          
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
        }
      }
    });
  },

  // 格式化开始时间
  formatStartTime: function(timeStr) {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now - date;
    const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (diffDays === 0) {
      return '今天 ' + this.formatTime(date);
    } else if (diffDays === 1) {
      return '昨天 ' + this.formatTime(date);
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  },

  // 格式化时间
  formatTime: function(date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },

  // 格式化最后活跃时间
  formatLastActive: function(timeStr) {
    if (!timeStr) return '';
    
    const date = new Date(timeStr);
    const now = new Date();
    const diff = now - date;
    const diffMinutes = Math.floor(diff / (1000 * 60));
    const diffHours = Math.floor(diff / (1000 * 60 * 60));
    const diffDays = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (diffMinutes < 1) {
      return '刚刚';
    } else if (diffMinutes < 60) {
      return `${diffMinutes}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  },

  // 获取人设名称
  getPersonaName: function(persona) {
    const personaConfig = this.data.personas[persona];
    return personaConfig ? personaConfig.name : '未知';
  }
}); 